import { Breadcrumb, Button, Form, DatePicker, Select, Radio, Table, Card, Tag, Space, Popconfirm } from 'antd';
// 引入汉化包 时间选择器显示中文
import locale from 'antd/es/date-picker/locale/zh_CN';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import img404 from "@/assets/404.png";
import { Link, useNavigate } from 'react-router-dom';
import './index.scss';
import { useChannel } from '@/hooks/useChannel';
import { getArticleListAPI, delArticleAPI } from "@/apis/article";
import { useEffect, useState } from 'react';

const { RangePicker } = DatePicker;
const { Option } = Select;

const Article = () => {
      // 获取频道列表
      const { channelList } = useChannel();
      // 路由跳转
      const navigator = useNavigate();


      // 定义枚举
      const status = {
            1: <Tag color='warning'>待审核</Tag>,
            2: <Tag color='success'>审核通过</Tag>
      }
      const columns = [
            {
                  title: '封面',
                  dataIndex: 'cover',
                  key: 'cover',
                  align: 'center',
                  render: cover => {
                        return <img src={cover.images[0] || img404} width={80} height={60} alt='' />
                  }
            },
            {
                  title: '标题',
                  dataIndex: 'title',
                  key: 'title',
                  align: 'center',
            },
            {
                  title: '状态',
                  dataIndex: 'status',
                  key: 'status',
                  align: 'center',
                  // data - 后端返回的状态status 根据它做条件渲染
                  // data === 1 => 待审核
                  // data === 2 =>审核通过
                  render: data => status[data]
            },
            {
                  title: '发布时间',
                  dataIndex: 'pubdate',
                  key: 'pubdate',
                  align: 'center',
            },
            {
                  title: '阅读数',
                  dataIndex: 'read_count',
                  key: 'read_count',
                  align: 'center',
            },
            {
                  title: '评论数',
                  dataIndex: 'like_count',
                  key: 'like_count',
                  align: 'center',
            },
            {
                  title: '评论数',
                  dataIndex: 'like_count',
                  key: 'like_count',
                  align: 'center',
            },
            {
                  title: '操作',
                  align: 'center',
                  render: data => {
                        return (
                              <Space size="middle">
                                    <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => navigator(`/publish?id=${data.id}`)} />
                                    <Popconfirm
                                          title="删除文章"
                                          description="确认要删除当前文章吗?"
                                          onConfirm={() => onConfirm(data)}
                                          okText="Yes"
                                          cancelText="No"
                                    >
                                          <Button type="primary" danger shape="circle" icon={<DeleteOutlined />} />
                                    </Popconfirm>
                              </Space>
                        )
                  }
            }
      ]


      // 获取文章列表
      const [dataList, setDataList] = useState([]);
      // 表格总条数
      const [count, setCount] = useState(0);

      // 筛选功能
      const [reqData, setReqData] = useState({
            status: '',
            channel_id: '',
            begin_pubdate: '',
            end_pubdate: '',
            page: 1,
            per_page: 3,
      })
      useEffect(() => {
            async function getDataList() {
                  const res = await getArticleListAPI(reqData)
                  setDataList(res.data.results)
                  setCount(res.data.total_count)
            }
            getDataList()
      }, [reqData])


      //获取筛选数据
      const onFinish = (formValue) => {
            setReqData({
                  ...reqData,
                  status: formValue.status,
                  channel_id: formValue.channel_id,
                  begin_pubdate: formValue.date ? formValue.date[0].format('YYYY-MM-DD') : '',
                  end_pubdate: formValue.date ? formValue.date[1].format('YYYY-MM-DD') : '',
            })
      }


      // 分页
      const onPageChange = (page) => {
            setReqData({
                  ...reqData,
                  page
            })
      }

      // 删除
      const onConfirm = async (data) => {
            await delArticleAPI(data.id)
            setReqData({
                  ...reqData
            })
      }

      return (
            <div className="article">
                  <Card
                        title={
                              <Breadcrumb
                                    items={[
                                          { title: <Link to={'/'}>首页</Link> },
                                          { title: '文章列表' },
                                    ]} />
                        }
                        style={{ marginBottom: 20 }}
                  >
                        <Form rm onFinish={onFinish} initialValues={{ status: '' }}>

                              <Form.Item name="status" label="状态">
                                    <Radio.Group>
                                          <Radio value={''}>全部</Radio>
                                          <Radio value={1}>草稿</Radio>
                                          <Radio value={2}>审核通过</Radio>
                                    </Radio.Group>
                              </Form.Item>

                              <Form.Item name="channel_id" label="频道">
                                    <Select placeholder="请选择文章频道" style={{ width: 150 }} allowClear>
                                          {channelList.map(item =>
                                                <Option key={item.id} value={item.id} >{item.name}</Option>
                                          )}
                                    </Select>
                              </Form.Item>


                              {/* 富文本编辑器 */}
                              <Form.Item name="date" label="日期">
                                    <RangePicker locale={locale} />
                              </Form.Item>

                              <Form.Item>
                                    <Button type="primary" htmlType="submit">
                                          筛选
                                    </Button>
                              </Form.Item>
                        </Form>
                  </Card>

                  {/* 表格区域 */}
                  <Card title={`根据筛选调条件共查询到 ${count} 条结果`}>
                        <Table
                              dataSource={dataList}
                              columns={columns}
                              rowKey={(record) => record.id}
                              pagination={{
                                    total: count,
                                    pageSize: reqData.per_page,
                                    onChange: onPageChange
                              }}
                        />
                  </Card>
            </div>
      )
}

export default Article;